# -*- coding: utf-8 -*-
# Author   : ZhangQing
# Time     : 2025-08-05 23:21
# File     : user_routes.py
# Project  : codebuddy_craft
# Desc     : 用户API路由

# backend/api/user_routes.py
"""
用户API路由 👤

处理用户管理相关功能
"""

from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, func, or_
from typing import List, Optional

from backend.database.connection import get_db
from backend.models.user import User
from backend.api.auth_routes import require_auth, get_current_user
from backend.utils.logger import get_logger
from backend.schemas.user import UserResponse, UserUpdateRequest, UserSearchResponse

router = APIRouter()
logger = get_logger(__name__)


@router.get("/profile", response_model=UserResponse)
async def get_user_profile(current_user: User = Depends(require_auth)):
    """获取用户资料 📋"""
    return UserResponse.from_orm(current_user)


@router.put("/profile", response_model=UserResponse)
async def update_user_profile(
        user_update: UserUpdateRequest,
        current_user: User = Depends(require_auth),
        db: AsyncSession = Depends(get_db)
):
    """更新用户资料 ✏️"""

    # 检查邮箱是否被其他用户使用
    if user_update.email and user_update.email != current_user.email:
        result = await db.execute(
            select(User).where(
                User.email == user_update.email,
                User.id != current_user.id
            )
        )
        if result.scalar_one_or_none():
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="邮箱已被其他用户使用"
            )

    # 更新用户信息
    update_data = user_update.dict(exclude_unset=True)
    for field, value in update_data.items():
        setattr(current_user, field, value)

    await db.commit()
    await db.refresh(current_user)

    logger.success(f"用户资料更新成功: {current_user.username}")

    return UserResponse.from_orm(current_user)


@router.get("/search", response_model=List[UserSearchResponse])
async def search_users(
        q: str = Query(..., min_length=2, description="搜索关键词"),
        limit: int = Query(10, le=50, description="返回数量限制"),
        current_user: Optional[User] = Depends(get_current_user),
        db: AsyncSession = Depends(get_db)
):
    """搜索用户 🔍"""

    # 构建搜索查询
    search_filter = or_(
        User.username.ilike(f"%{q}%"),
        User.full_name.ilike(f"%{q}%"),
        User.email.ilike(f"%{q}%")
    )

    query = select(User).where(
        User.is_active == True,
        search_filter
    ).limit(limit)

    # 如果是未认证用户，只返回公开信息
    if not current_user:
        query = query.where(User.is_verified == True)

    result = await db.execute(query)
    users = result.scalars().all()

    return [UserSearchResponse.from_orm(user) for user in users]


@router.get("/{user_id}", response_model=UserResponse)
async def get_user_by_id(
        user_id: str,
        current_user: Optional[User] = Depends(get_current_user),
        db: AsyncSession = Depends(get_db)
):
    """根据ID获取用户信息 🆔"""

    result = await db.execute(select(User).where(User.id == user_id))
    user = result.scalar_one_or_none()

    if not user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户不存在"
        )

    # 权限检查：只有用户本人或已认证用户可以查看详细信息
    if not current_user or (current_user.id != user.id and not user.is_verified):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="没有权限查看该用户信息"
        )

    return UserResponse.from_orm(user)


@router.delete("/account")
async def delete_user_account(
        current_user: User = Depends(require_auth),
        db: AsyncSession = Depends(get_db)
):
    """删除用户账户 🗑️"""

    # 软删除：将用户标记为非活跃状态
    current_user.is_active = False
    current_user.username = f"deleted_{current_user.id}"
    current_user.email = f"deleted_{current_user.id}@deleted.com"

    await db.commit()

    logger.warning(f"用户账户已删除: {current_user.id}")

    return {"message": "账户已成功删除"}


@router.get("/{user_id}/stats")
async def get_user_stats(
        user_id: str,
        current_user: Optional[User] = Depends(get_current_user),
        db: AsyncSession = Depends(get_db)
):
    """获取用户统计信息 📊"""

    # 检查用户是否存在
    result = await db.execute(select(User).where(User.id == user_id))
    user = result.scalar_one_or_none()

    if not user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户不存在"
        )

    # 权限检查
    if not current_user or (current_user.id != user.id and not user.is_verified):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="没有权限查看该用户统计信息"
        )

    # 获取统计数据
    from backend.models.project import Project

    # 项目统计
    project_count_result = await db.execute(
        select(func.count(Project.id)).where(Project.owner_id == user_id)
    )
    project_count = project_count_result.scalar()

    # 总代码行数统计
    total_lines_result = await db.execute(
        select(func.sum(Project.total_lines)).where(Project.owner_id == user_id)
    )
    total_lines = total_lines_result.scalar() or 0

    return {
        "user_id": user_id,
        "username": user.username,
        "project_count": project_count,
        "total_lines": total_lines,
        "join_date": user.created_at.isoformat() if user.created_at else None,
        "last_active": user.last_login_at.isoformat() if user.last_login_at else None
    }
